package com.huikeportal.service.impl;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import net.rubyeye.xmemcached.MemcachedClient;
//import net.rubyeye.xmemcached.exception.MemcachedException;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.service.MemcachedService;


@Service("MemcachedService")
public class MemcachedServiceImpl implements MemcachedService {
	
//	@Autowired
//	private MemcachedClient memcachedClient;
	
	
	
	public MemcachedServiceImpl() {
		getOpen();
	}
	// 消息Properties存放对象
	private boolean open=false;
	/**
	 * 读取消息内容
	 * 
	 * @throws Exception
	 */
	private  void getOpen(){
		Properties properties = new Properties();
		String temp = MessageManager.class.getResource("/").getPath()
				.replaceAll("%20", " ");
		InputStream in;
		try {
			in = new BufferedInputStream(new FileInputStream(temp
					+ "memcached.properties"));
			properties.load(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String openStr="";
		if(properties.getProperty("memcached.Open")!=null){
			openStr=properties.getProperty("memcached.Open").toString();
		}
		if(openStr.endsWith("true")){
			open=true;
		};
	}
  
	

/** 
 * @param method 
 * @param assignCacheKey 
 * @return 
 * @throws IllegalArgumentException 
 */  
	public String getCacheKey(Object[] args, String cacheKeyExpression) throws NoSuchMethodException,  
        IllegalArgumentException {  
    if (cacheKeyExpression == null || cacheKeyExpression.trim().equals("")) {  
        throw new IllegalArgumentException("This assignCacheKey is not valid on a method.");  
    }  
  
    // 解析assignCacheKey表达式,格式如： ${param0}+ hello + ${param1.name(key)}  
    StringBuffer sbCacheKey = new StringBuffer(128);  
    String[] params = cacheKeyExpression.replaceAll(" ", "").split("[+]");  
    for (int i = 0; i < params.length; i++) {  
        if (params[i] == null || "".equals(params[i].trim())) {  
            continue;  
        }  
  
        Pattern pattern = Pattern.compile("^([$][{]).*[}]$");  
        Matcher matcher = pattern.matcher(params[i]);  
        if (matcher.find()) {  
            // 根据参数获取参数值：${coupon.name}  
            String param = params[i].substring(2, params[i].length() - 1);  
            sbCacheKey.append(this.getArguValue(args, param));  
        } else {  
            sbCacheKey.append(params[i]);  
        }  
    }  
  
    return sbCacheKey.toString();  
}  
  
/** 
 * 根据参数名获取参数值 
 * 
 * @param args 
 * @param param 
 * @return 
 * @throws IllegalArgumentException 
 * @throws NoSuchMethodException 
 */  
private String getArguValue(Object[] args, String params) throws NoSuchMethodException, IllegalArgumentException {  
    String[] arrParam = params.split("[.]");  
    if (arrParam[0] == null || "".equals(arrParam[0])) {  
        new IllegalArgumentException("This assignCacheKey is not valid on a method.");  
    }  
  
    // 方法入参列表中匹配当前参数对象  
    int index = Integer.parseInt(arrParam[0].replaceAll("param", ""));  
    Object currObject = args[index];  
  
    try {  
        for (int i = 1; i < arrParam.length; i++) {  
            // 根据参数获取参数值：name(key)  
            String param=arrParam[i];  
            Pattern pattern = Pattern.compile("([(]).*[)]$");  
            Matcher matcher = pattern.matcher(param);  
            if (matcher.find()) {  
                String paramName = param.substring(0, param.indexOf('('));  
                String paramKey = param.substring(param.indexOf('(')+1, param.length() - 1);  
                currObject = BeanUtils.getMappedProperty(currObject, paramName, paramKey);  
            } else {  
                currObject = BeanUtils.getProperty(currObject, param);  
            }  
        }  
    } catch (Exception ex) {  
        new IllegalArgumentException("This assignCacheKey is not valid on a method.");  
    }  
  
    return currObject!=null? currObject.toString():"";  
}  
	
	
	
	/**
	 * 保存缓存
	 * @return boolean
	 * @throws MemcachedException 
	 * @throws InterruptedException 
	 * @throws TimeoutException 
	 * 
	 */
	public boolean setMemcached(String key,Object object){
		boolean result=false;
//		try {
//			if(!open){
//				return false;
//	        }else{
////	        	result= memcachedClient.set(key, 36000, object);
//	        }
//		} catch (TimeoutException e) {
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		} catch (MemcachedException e) {
//			e.printStackTrace();
//		}  
		return result;
	}
	/**
	 * 根据key取缓存
	 * @param String key
	 * @return Object
	 * @throws TimeoutException
	 * @throws InterruptedException
	 * @throws MemcachedException
	 */
	
	public Object getMemcached(String key){
		Object result=null;
//		try {
//			if(!open){
//				return null;
//	        }else{
//			result= memcachedClient.get(key);
//	        }
//		} catch (TimeoutException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (MemcachedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}  
		return result;
	}
	/**
	 * @category 更新已有记录，并设置超时天数 
	 * @category 前提：该值在缓存中已经存在
	 * @param key
	 * @param object
	 * @return
	 * @throws TimeoutException
	 * @throws InterruptedException
	 * @throws MemcachedException
	 */
	public boolean replaceMemcached(String key,Object object){
		boolean result=false;
//		try {
//			if(!open){
//				return false;
//	        }else{
//	        	result= memcachedClient.replace(key, 36000, object);
//	        }
//		} catch (TimeoutException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (MemcachedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}  
		return result;
	}
	/**
	 * 根据key移除缓存
	 * @param key
	 * @return
	 * @throws TimeoutException
	 * @throws InterruptedException
	 * @throws MemcachedException
	 */
	public boolean deleteMemcached(String key){
		boolean result=false;
//		try {
//			if(!open){
//				return false;
//	        }else{
//	        	result=memcachedClient.delete(key);
//	        }
//		} catch (TimeoutException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (InterruptedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (MemcachedException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		return result;
	}

}
